package com.yoyo.framework.shiro.web.session;

import com.yoyo.common.utils.Threads;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionValidationScheduler;
import org.apache.shiro.session.mgt.ValidatingSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zyl
 * @Date 2021/7/18 -10:39
 * 自定义任务调度器
 */
@Component
@Slf4j
public class SpringSessionValidationScheduler implements SessionValidationScheduler {

    @Autowired
    @Qualifier("scheduledExecutorService")
    private ScheduledExecutorService executorService;

    private volatile boolean enabled = false;

    @Autowired
    @Qualifier("sessionManager")
    @Lazy
    private ValidatingSessionManager sessionManager;

    // 相隔多久检查一次session的有效性，单位毫秒，默认就是10分钟
    @Value("${shiro.session.validationInterval}")
    private long sessionValidationInterval;

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }

    public void setSessionValidationInterval(long sessionValidationInterval) {
        this.sessionValidationInterval = sessionValidationInterval;
    }

    @Override
    public void enableSessionValidation() {
        enabled = true;
        log.debug("Scheduling session validation job using Spring scheduler with session validation interval of {} ms", sessionValidationInterval);
        try {
            executorService.scheduleAtFixedRate(() -> {
                        if (enabled) {
                            sessionManager.validateSessions();
                        }
                    },
                    1000, sessionValidationInterval * 60 * 1000, TimeUnit.SECONDS);
            this.enabled = true;
            log.debug("session validation job successfully scheduled with spring scheduled .");
        } catch (Exception e) {
            log.error("Error starting the Spring Scheduler session validation job Session validation may not occur", e);
        }


    }

    @Override
    public void disableSessionValidation() {
        log.debug("Stopping Spring Scheduler session validation job..");
        if (this.enabled) {
            Threads.shutdownAndAwaitTermination(executorService);
        }
        this.enabled = false;
    }
}
